package hibernate;

import javax.ejb.Stateless;
import javax.ejb.LocalBean;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author Igor Kovb
 */
@Stateless
@LocalBean
public class ProductDAO {

    ElementDAOClass<Product> coreProdDAO;
    ElementDAOClass<ProductCategory> coreProdCatDAO;

    public ProductDAO() {
        coreProdDAO = new ElementDAOClass<Product>(Product.class);
        coreProdCatDAO = new ElementDAOClass<ProductCategory>(ProductCategory.class);
    }

     //-----------------------------------Product DAO section

    public List<Product> getAllProducts() {
        List<Product> res = (List<Product>) coreProdDAO.getAllElements();
        return res;
    }

    public Product getProductByID(int pID) {
        Product res = (Product) coreProdDAO.getElementByID(pID);
        return res;
    }

    public void addAndSaveNewProduct(Product newProduct) {
        coreProdDAO.addElement(newProduct);
    }

    public Product createEmptyProduct() {
        return new Product();
    }

    public void deleteProduct(Product productToDelete) {
        coreProdDAO.deleteElement(productToDelete);
    }

    public void updateProduct(Product productToUpdate) {
        coreProdDAO.updateElement(productToUpdate);
    }

    public List<Product> getAllProductsInCategory(int productCategoryID) {
        List<Product> res = null;
        Session session = null;

        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            // creating a query			
            Query query = session.createQuery("from Product where categoryID = :pid");

            query.setParameter("pid", productCategoryID);

            res = query.list();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return res;
    }

     //-----------------------------------ProductCategory DAO section

    public List<ProductCategory> getAllProductCategories() {
        List<ProductCategory> res = (List<ProductCategory>) coreProdCatDAO.getAllElements();
        return res;
    }

    public ProductCategory getProductCategoryByID(int pID) {
        ProductCategory res = (ProductCategory) coreProdCatDAO.getElementByID(pID);
        return res;
    }

    public void addAndSaveNewProductCategory(ProductCategory newProductCategory) {
        coreProdCatDAO.addElement(newProductCategory);
    }

    public ProductCategory createEmptyProductCategory() {
        return new ProductCategory();
    }

    public void deleteProductCategory(ProductCategory productCategoryToDelete) {
        coreProdCatDAO.deleteElement(productCategoryToDelete);
    }

    public void updateProductCategory(ProductCategory productCategoryToUpdate) {
        coreProdCatDAO.updateElement(productCategoryToUpdate);
    }
    
}
